import {ref} from "vue";
import {watch} from "vue-demi";
import {resolveUnref, tryOnMounted} from "@vueuse/shared";
import {useEventListener, useResizeObserver} from "@vueuse/core"

export const useElementBounding = (target, options = {}) => {
	const {
		reset = true,
		windowResize = true,
		windowScroll = true,
		immediate = true
	} = options;
	const height = ref(0);
	const bottom = ref(0);
	const left = ref(0);
	const right = ref(0);
	const top = ref(0);
	const width = ref(0);
	const x = ref(0);
	const y = ref(0);

	function update(flag = false) {
		const el = unrefElement(target);
		if (!el) {
			if (reset) {
				height.value = 0;
				bottom.value = 0;
				left.value = 0;
				right.value = 0;
				top.value = 0;
				width.value = 0;
				x.value = 0;
				y.value = 0;
			}
			return;
		}
		const rect = el.getBoundingClientRect();
		height.value = rect.height;
		bottom.value = rect.bottom;
		left.value = rect.left;
		right.value = rect.right;
		top.value = rect.top + 86;
		width.value = rect.width;
		x.value = rect.x;
		y.value = rect.y;
		if (flag) {
			return {
				top
			};
		}
	}

	useResizeObserver(target, update);
	watch(() => unrefElement(target), (ele) => !ele && update());
	useEventListener("scroll", update, {passive: true});
	if (windowScroll)
		useEventListener("scroll", update, {passive: true});
	if (windowResize)
		useEventListener("resize", update, {passive: true});
	tryOnMounted(() => {
		if (immediate)
			update();
	});
	return {
		height,
		bottom,
		left,
		right,
		top,
		width,
		x,
		y,
		update
	};
};

function unrefElement(elRef) {
	var _a;
	const plain = resolveUnref(elRef);
	return (_a = plain == null ? void 0 : plain.$el) != null ? _a : plain;
}
